'use strict';
const BaseController = require('./base');
const _ = require('lodash');

class CommonController extends BaseController {
  /**
   * 下载视频
   *
   * Method: GET
   * Path: /api/v1/common/download-video
   */
  async downloadVideo() {
    const { ctx } = this;
    const rules = {
      video_url: { type: 'string', required: true, empty: false, trim: true },
      sign: { type: 'string', required: true, empty: false, trim: true },
    };
    try {
      ctx.validate(rules, ctx.query);
    } catch (error) {
      ctx.logger.info(error);
      error.message = `${error.message}: ${error.errors[0].field} ${error.errors[0].message}`;
      error.code = -400;
      throw error;
    }
    const { video_url, sign } = ctx.query;
    console.log('video_url', video_url);
    // 校验签名
    const v_sign = ctx.helper.signature(encodeURIComponent(video_url));
    if (!_.isEqual(v_sign, sign)) {
      this.logger.error(v_sign, sign);
      this.logger.error('video_url', video_url);
      throw Error('签名错误');
    }
    const result = await ctx.curl(video_url, {
      streaming: true,
    });
    ctx.attachment(`${ctx.helper.generateOrderNo()}.mp4`);
    ctx.set('content-length', result.headers['content-length']);
    ctx.body = result.res;
  }
}

module.exports = CommonController;
